const logger = require('../utils/log4js').api
const qiniu = require('qiniu')
const mac = new qiniu.auth.digest.Mac(process.env.QINIU_AK, process.env.QINIU_SK)
const config = new qiniu.conf.Config()
config.zone = qiniu.zone.Zone_z2
const bucketManager = new qiniu.rs.BucketManager(mac, config)

exports.getContentList = async function (ctx, next) {
  try {
    var data = await new Promise((resolve, reject) => {
      bucketManager.listPrefix(process.env.QINIU_BUCKET, {}, (err, resBody, resInfo) => {
        if (err) { reject(err) }
        const data = []
        resBody.items.forEach(item => {
          data.push(item.key)
        })
        resolve(data)
      })
    })
    ctx.body = {
      success: true,
      message: 'success',
      data: data
    }
  } catch (err) {
    logger.info('qiniu service unavaliable')
    ctx.body = {
      success: false,
      message: 'qiniu service unavaliable'
    }
  }
}

exports.getUpLoadToken = function (ctx, next) {
  var options = {
    scope: process.env.QINIU_BUCKET
  }
  var reqPath = ctx.request.path.split('/')
  var tokenType = reqPath[reqPath.length - 1]
  if (!tokenType)tokenType = reqPath[reqPath.length - 2]
  var prefix = ''
  if (tokenType === 'chatroom') {
    options.scope += ':chatroom_cache_'
    options.isPrefixalScope = 1
    prefix = 'chatroom_cache_'
  }
  var putPolicy = new qiniu.rs.PutPolicy(options)
  var token = putPolicy.uploadToken(mac)
  ctx.body = {
    success: true,
    message: 'success',
    data: {
      uploadtoken: token,
      uploadurl: process.env.QINIU_UPLOADURL,
      cdnurl: process.env.QINIU_CDNURL,
      prefix
    }
  }
}
